package com.zygh.policeasset.config;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

@ServerEndpoint("/webSocket/{userId}")
@Component
/* loaded from: police-asset-2.0-0.0.1-SNAPSHOT.jar:BOOT-INF/classes/com/zygh/policeasset/config/WebSocketServer.class */
public class WebSocketServer {
    private static Log log = LogFactory.get(WebSocketServer.class);
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    private Session session;
    private String userId = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            addOnlineCount();
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount(), new Object[0]);
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:" + userId + ",网络异常!!!!!!", new Object[0]);
        }
    }

    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(this.userId)) {
            webSocketMap.remove(this.userId);
            subOnlineCount();
        }
        log.info("用户退出:" + this.userId + ",当前在线人数为:" + getOnlineCount(), new Object[0]);
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("用户消息:" + this.userId + ",报文:" + message, new Object[0]);
        if (StringUtils.isNotBlank(message)) {
            try {
                JSONObject jsonObject = JSON.parseObject(message);
                jsonObject.put("fromUserId", (Object) this.userId);
                String toUserId = jsonObject.getString("toUserId");
                if (!StringUtils.isNotBlank(toUserId) || !webSocketMap.containsKey(toUserId)) {
                    log.error("请求的userId:" + toUserId + "不在该服务器上", new Object[0]);
                } else {
                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage(), new Object[0]);
        error.printStackTrace();
    }

    public static void sendInfo(String message, @PathParam("userId") String userId) {
        log.info("发送消息到:" + userId + "，报文:" + message, new Object[0]);
        if (org.springframework.util.StringUtils.isEmpty(userId)) {
            sendtoAll(message);
        } else if (!StringUtils.isNotBlank(userId) || !webSocketMap.containsKey(userId)) {
            log.error("用户" + userId + ",不在线！", new Object[0]);
        } else {
            try {
                webSocketMap.get(userId).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void sendtoAll(String message) {
        Iterator it = webSocketMap.keySet().iterator();
        while (it.hasNext()) {
            try {
                webSocketMap.get((String) it.next()).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        onlineCount--;
    }
}